<?php

namespace Apps\Common\Libs;


use Apps\Common\Models\UserOrder;
use Apps\Common\Models\UserOrderGoods;
use PhalconPlus\Common\Component;
use PhalconPlus\Common\Util;
use WeiXin\Pay as WeiXinPay;

class Pay extends Component
{
    public function weiXinUnifiedOrderByApp($orderId=0, $orderLongId=0)
    {
        $orderInfo = null;
        if($orderId > 0){
            $orderInfo = UserOrder::findFirst('order_id = ' . $orderId);
        } elseif($orderLongId > 0) {
            $orderInfo = UserOrder::findFirst('order_long_id = ' . $orderLongId);
        }
        if(!$orderInfo) {
            return false;
        }
        $orderId = $orderInfo->order_id;
        $orderLongId = $orderInfo->order_long_id;
        $totalFee = $orderInfo->order_money;
        $titleArr = [];
        // 商品信息
        $goods = UserOrderGoods::query()
            ->columns('service_name name')
            ->where('order_id = :oid:', ['oid' => $orderId])
            ->leftJoin('Apps\Common\Models\BeautyParlorService', 'service_id = goods_id', 'bps')
            ->execute();
        foreach($goods as $d) {
            $titleArr[] = $d->name;
        }
        $title = implode(',', $titleArr);
        $payConfig = include APP_COMMON_PATH . "base-config/pay.php";
        $wxPay = new WeiXinPay($payConfig['weixin']);
        $info = $wxPay->unifiedOrder($orderLongId, $title, $totalFee, 'APP');
        if($info == false) {
            return false;
        }
        return $info['prepayId'];
    }

    public function weiXin2AppPay($orderId=0, $orderLongId=0)
    {
        $perpayid = $this->weiXinUnifiedOrderByApp($orderId, $orderLongId);
        if($perpayid == false) {
            return false;
        }
        $payConfig = include APP_COMMON_PATH . "base-config/pay.php";
        $weixinConfig = $payConfig['weixin'];
        $params = [
            'appid' => $weixinConfig['appId'],
            'partnerid' => $weixinConfig['mchId'],
            'prepayid' => $perpayid,
            'package' => 'Sign=WXPay',
            'noncestr' => Util::RandStr(10),
            'timestamp' => time()
        ];
        $pay = new \WeiXin\Pay($weixinConfig);
        $params['sign'] = $pay->getSign($params);
        $params['_package'] = $params['package'];
        unset($params['package']);
        return $params;
    }
}
